package face.pay.task.card.service.impl;

import face.pay.constant.CardMessageType;
import face.pay.constant.SharingAccountType;
import face.pay.dao.CpnCardMessageDao;
import face.pay.dao.SharingAccountDao;
import face.pay.dao.SharingOrderInfoDao;
import face.pay.entity.CpnCardMessage;
import face.pay.entity.SharingOrderInfo;
import face.pay.task.card.service.ISharingAccountMessageService;
import face.pay.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SharingAccountMessageServiceImpl implements ISharingAccountMessageService {

    @Autowired
    SharingOrderInfoDao sharingOrderInfoDao;

    @Autowired
    CpnCardMessageDao messageDao;


    @Transactional(rollbackFor = Exception.class)
    public  void checkSharing(){

        log.info("检测投放平台 分账成功到MARKET的订单");

        SharingOrderInfo sharingOrderInfo = new SharingOrderInfo();
        sharingOrderInfo.setStatus(1);
        sharingOrderInfo.setType(SharingAccountType.MARKET);

        /**
         * 查询需要发送消息的 分账通知
         */
        List<SharingOrderInfo> list =  this.sharingOrderInfoDao.queryData(sharingOrderInfo);

        List<CpnCardMessage> messageList = new ArrayList<>();
        log.info("数量 :"+list.size());
        if(list.size()>0){
            for(SharingOrderInfo orderInfo :list ){

                CpnCardMessage cpnCardMessage =  new CpnCardMessage();
                cpnCardMessage.setOrderId(orderInfo.getOrderId());
                cpnCardMessage.setCardDetailId(orderInfo.getCardDetailId());
                cpnCardMessage.setRefId(orderInfo.getId());
                cpnCardMessage.setType(CardMessageType.CONSUME);
                cpnCardMessage.setStatus(0);
                cpnCardMessage.setCount(0);
                Date nowTime = DateUtil.addMinute(new Date(),5);
                cpnCardMessage.setNextTime(DateUtil.dateFormat(nowTime));
                messageList.add(cpnCardMessage);

            }
            log.info("更新状态");
            sharingOrderInfoDao.updateBatchStatus(list);
            log.info("插入消息");
            messageDao.insertBatch(messageList);
            log.info("结束");
        }


    }
}
